package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Override
    public Result<PageResult> findAll(DishPageQueryDTO pageQueryDTO) {
        PageResult result = new PageResult();
        result.setTotal(dishMapper.count());
        result.setRecords(dishMapper.findAll(pageQueryDTO));
        return Result.success(result);
    }

    @Override
    public void status(Integer status, int id) {
        // 更新状态
        dishMapper.status(status, id);
    }

    @Override
    public void delete(List<Integer> ids) {
        //判断菜品是否处于可删除状态
        for (Integer id : ids) {
            Dish dish = dishMapper.findById(id);
            if (dish.getStatus() == 1) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            dishMapper.delete(id);
        }
    }

    @Override
    public Result<PageResult> queryDish(DishPageQueryDTO queryDTO) {
        List<Setmeal> setmeals = dishMapper.queryDish(queryDTO);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(setmeals.size());
        pageResult.setRecords(setmeals);
        System.out.println(pageResult);
        return Result.success(pageResult);
    }

    @Override
    public void updatastatus(Integer status, int id) {
        System.out.println(status+":"+id);
        dishMapper.updatastatus(status, id);
    }

    @Override
    public void deletes(List<Integer> ids) {
        for (Integer id : ids) {
            dishMapper.deletes(id);
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
